/**
 * 音频管理模块
 * 处理番茄时钟的声音提醒功能
 */

class AudioManager {
    constructor() {
        this.audioElement = null;
        this.isEnabled = true;
        this.volume = 0.7;
        this.currentSoundType = 'bell'; // 默认音效类型
        
        // 不同状态的提示音配置
        this.soundConfig = {
            work_complete: {
                frequencies: [800, 1000, 800],
                durations: [0.3, 0.2, 0.4],
                volumes: [0.4, 0.3, 0.4],
                waveType: 'sine',
                gap: 0.1,
                description: '工作完成 - 清脆提醒'
            },
            break_complete: {
                frequencies: [523.25, 659.25, 783.99], // C5, E5, G5
                durations: [0.8, 0.8, 1.2],
                volumes: [0.3, 0.25, 0.3],
                waveType: 'triangle',
                gap: 0.2,
                description: '休息结束 - 温和钟声'
            },
            long_break_complete: {
                frequencies: [523.25, 659.25, 783.99, 1046.50], // C5, E5, G5, C6
                durations: [0.2, 0.2, 0.2, 0.6],
                volumes: [0.3, 0.35, 0.4, 0.45],
                waveType: 'triangle',
                gap: 0.05,
                description: '长休息结束 - 成功音效'
            },
            gentle_reminder: {
                frequencies: [440, 554.37], // A4, C#5
                durations: [1.0, 1.5],
                volumes: [0.2, 0.15],
                waveType: 'sine',
                gap: 0.3,
                fadeIn: 0.3,
                fadeOut: 0.5,
                description: '温和提醒 - 不打断专注'
            }
        };
        
        // 可用的音频文件 (支持多种格式)
        this.soundFiles = {
            bell: ['assets/sounds/bell.wav', 'assets/sounds/bell.mp3'],
            chime: ['assets/sounds/chime.wav', 'assets/sounds/chime.mp3'],
            ding: ['assets/sounds/ding.wav', 'assets/sounds/ding.mp3'],
            notification: ['assets/sounds/notification.wav', 'assets/sounds/notification.mp3'],
            gentle: ['assets/sounds/gentle.wav', 'assets/sounds/gentle.mp3'],
            success: ['assets/sounds/success.wav', 'assets/sounds/success.mp3']
        };

        // 音频文件描述
        this.soundDescriptions = {
            bell: '清脆铃声 - 经典提醒音',
            chime: '温和钟声 - 适合休息提醒',
            ding: '轻快叮声 - 简洁明快',
            notification: '现代通知音 - 科技感',
            gentle: '温和提示音 - 不打断专注',
            success: '成功提示音 - 增强成就感'
        };
        
        this.init();
    }
    
    /**
     * 初始化音频管理器
     */
    init() {
        // 尝试获取HTML中的音频元素
        this.audioElement = document.getElementById('notificationSound');
        
        // 创建Web Audio Context用于生成提示音
        try {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
            console.log('AudioContext initialized');
        } catch (error) {
            console.warn('Web Audio API not supported:', error);
            this.audioContext = null;
        }
        
        // 从本地存储加载设置
        this.loadSettings();
        
        console.log('AudioManager initialized');
    }
    
    /**
     * 播放通知音
     * @param {string} type - 通知类型 (work_complete, break_complete, long_break_complete)
     */
    playNotification(type = 'work_complete') {
        if (!this.isEnabled) {
            console.log('Audio notifications disabled');
            return;
        }
        
        // 首先尝试播放预设音频文件
        if (this.audioElement && this.audioElement.canPlayType) {
            this.playAudioFile();
        } else {
            // 如果没有音频文件，使用Web Audio API生成提示音
            this.playGeneratedSound(type);
        }
    }
    
    /**
     * 播放音频文件
     * @param {string} soundType - 声音类型
     */
    playAudioFile(soundType) {
        const audioFiles = this.soundFiles[this.currentSoundType];
        if (!audioFiles || audioFiles.length === 0) {
            console.warn(`音频文件不存在: ${this.currentSoundType}，使用生成音`);
            this.playGeneratedSound(soundType);
            return;
        }

        // 尝试播放第一个可用的音频文件
        this.tryPlayAudioFiles(audioFiles, soundType, 0);
    }

    /**
     * 尝试播放音频文件列表中的文件
     * @param {Array} audioFiles - 音频文件路径列表
     * @param {string} soundType - 声音类型
     * @param {number} index - 当前尝试的文件索引
     */
    tryPlayAudioFiles(audioFiles, soundType, index) {
        if (index >= audioFiles.length) {
            console.warn('所有音频文件都无法播放，使用生成音');
            this.playGeneratedSound(soundType);
            return;
        }

        const audioFile = audioFiles[index];
        const audio = new Audio(audioFile);
        audio.volume = this.volume;
        audio.preload = 'auto';

        // 成功加载时播放
        audio.addEventListener('canplaythrough', () => {
            audio.play().catch(error => {
                console.warn(`音频文件播放失败 (${audioFile}):`, error);
                this.tryPlayAudioFiles(audioFiles, soundType, index + 1);
            });
        }, { once: true });

        // 加载失败时尝试下一个文件
        audio.addEventListener('error', () => {
            console.warn(`音频文件加载失败 (${audioFile})，尝试下一个`);
            this.tryPlayAudioFiles(audioFiles, soundType, index + 1);
        }, { once: true });

        // 设置超时
        setTimeout(() => {
            if (audio.readyState < 2) {
                console.warn(`音频文件加载超时 (${audioFile})，尝试下一个`);
                this.tryPlayAudioFiles(audioFiles, soundType, index + 1);
            }
        }, 1000);

        audio.load();
    }
    
    /**
     * 使用Web Audio API生成并播放提示音
     * @param {string} type - 声音类型
     */
    playGeneratedSound(type) {
        if (!this.audioContext) {
            console.warn('AudioContext not available, using fallback');
            this.playFallbackSound();
            return;
        }

        // 确保AudioContext处于运行状态
        if (this.audioContext.state === 'suspended') {
            this.audioContext.resume().then(() => {
                this.generateAndPlaySound(type);
            }).catch(error => {
                console.warn('Failed to resume AudioContext:', error);
                this.playFallbackSound();
            });
        } else {
            this.generateAndPlaySound(type);
        }
    }

    /**
     * 生成并播放音效
     * @param {string} type - 声音类型
     */
    generateAndPlaySound(type) {
        const config = this.soundConfig[type] || this.soundConfig.work_complete;

        try {
            const { frequencies, durations, volumes, waveType = 'sine', gap = 0, fadeIn = 0.1, fadeOut = 0.1 } = config;
            let startTime = this.audioContext.currentTime;

            frequencies.forEach((freq, index) => {
                const oscillator = this.audioContext.createOscillator();
                const gainNode = this.audioContext.createGain();

                oscillator.connect(gainNode);
                gainNode.connect(this.audioContext.destination);

                oscillator.frequency.setValueAtTime(freq, startTime);
                oscillator.type = waveType;

                const duration = durations[index] || durations[0];
                const volume = (volumes[index] || volumes[0] || 0.3) * this.volume;

                // 音量包络
                gainNode.gain.setValueAtTime(0, startTime);
                gainNode.gain.linearRampToValueAtTime(volume, startTime + fadeIn);
                gainNode.gain.linearRampToValueAtTime(volume, startTime + duration - fadeOut);
                gainNode.gain.linearRampToValueAtTime(0, startTime + duration);

                oscillator.start(startTime);
                oscillator.stop(startTime + duration);

                startTime += duration + gap;
            });

            console.log(`Generated sound played: ${config.description || type}`);
        } catch (error) {
            console.error('Error generating sound:', error);
            this.playFallbackSound();
        }
    }
    
    /**
     * 播放蜂鸣音序列
     * @param {Object} config - 音频配置
     */
    playBeepSequence(config) {
        const { frequency, duration, pattern } = config;
        let currentTime = this.audioContext.currentTime;
        
        pattern.forEach((intensity, index) => {
            if (intensity > 0) {
                this.playBeep(frequency, duration * intensity, currentTime);
            }
            currentTime += (duration * intensity + 100) / 1000; // 添加间隔
        });
    }
    
    /**
     * 播放单个蜂鸣音
     * @param {number} frequency - 频率
     * @param {number} duration - 持续时间（毫秒）
     * @param {number} startTime - 开始时间
     */
    playBeep(frequency, duration, startTime) {
        try {
            // 创建振荡器
            const oscillator = this.audioContext.createOscillator();
            const gainNode = this.audioContext.createGain();
            
            // 连接节点
            oscillator.connect(gainNode);
            gainNode.connect(this.audioContext.destination);
            
            // 设置参数
            oscillator.frequency.setValueAtTime(frequency, startTime);
            oscillator.type = 'sine';
            
            // 设置音量包络
            const durationInSeconds = duration / 1000;
            gainNode.gain.setValueAtTime(0, startTime);
            gainNode.gain.linearRampToValueAtTime(this.volume * 0.3, startTime + 0.01);
            gainNode.gain.exponentialRampToValueAtTime(0.01, startTime + durationInSeconds);
            
            // 播放
            oscillator.start(startTime);
            oscillator.stop(startTime + durationInSeconds);
            
        } catch (error) {
            console.error('Error playing beep:', error);
        }
    }
    
    /**
     * 回退方案：使用系统提示音
     */
    playFallbackSound() {
        try {
            // 尝试使用系统提示音
            const utterance = new SpeechSynthesisUtterance('');
            utterance.volume = 0;
            speechSynthesis.speak(utterance);
            
            // 或者尝试创建一个简单的音频
            console.log('\u0007'); // 系统铃声字符
        } catch (error) {
            console.warn('Fallback sound failed:', error);
        }
    }
    
    /**
     * 测试音频
     */
    testSound() {
        console.log('Testing notification sound...');
        this.playNotification('work_complete');
    }
    
    /**
     * 设置音效类型
     * @param {string} soundType - 音效类型
     */
    setSoundType(soundType) {
        if (this.soundFiles[soundType]) {
            this.currentSoundType = soundType;
            this.saveSettings();
        }
    }
    
    /**
     * 获取当前音效类型
     * @returns {string} 当前音效类型
     */
    getSoundType() {
        return this.currentSoundType;
    }
    
    /**
     * 获取所有可用音效类型
     * @returns {Array} 可用音效类型列表
     */
    getAvailableSoundTypes() {
        return Object.keys(this.soundFiles);
    }

    /**
     * 获取音效描述
     * @param {string} soundType - 音效类型
     * @returns {string} 音效描述
     */
    getSoundDescription(soundType) {
        return this.soundDescriptions[soundType] || soundType;
    }

    /**
     * 获取所有音效类型和描述
     * @returns {Object} 音效类型和描述的映射
     */
    getAllSoundDescriptions() {
        return this.soundDescriptions;
    }
    
    /**
     * 预览音效
     * @param {string} soundType - 要预览的音效类型
     */
    previewSound(soundType) {
        if (!soundType || !this.soundFiles[soundType]) {
            console.warn(`无效的音效类型: ${soundType}`);
            return;
        }

        console.log(`预览音效: ${soundType} - ${this.getSoundDescription(soundType)}`);

        // 尝试播放音频文件
        const audioFiles = this.soundFiles[soundType];
        this.tryPreviewAudioFiles(audioFiles, soundType, 0);
    }

    /**
     * 尝试预览音频文件列表中的文件
     * @param {Array} audioFiles - 音频文件路径列表
     * @param {string} soundType - 声音类型
     * @param {number} index - 当前尝试的文件索引
     */
    tryPreviewAudioFiles(audioFiles, soundType, index) {
        if (index >= audioFiles.length) {
            console.warn('所有音频文件都无法预览，使用生成音效');
            this.playGeneratedSound('work_complete');
            return;
        }

        const audioFile = audioFiles[index];
        const audio = new Audio(audioFile);
        audio.volume = this.volume;

        // 成功加载时播放
        const playAudio = () => {
            audio.play().catch(error => {
                console.warn(`音频文件预览失败 (${audioFile}):`, error);
                this.tryPreviewAudioFiles(audioFiles, soundType, index + 1);
            });
        };

        // 加载失败时尝试下一个文件
        const handleError = () => {
            console.warn(`音频文件加载失败 (${audioFile})，尝试下一个`);
            this.tryPreviewAudioFiles(audioFiles, soundType, index + 1);
        };

        audio.addEventListener('canplaythrough', playAudio, { once: true });
        audio.addEventListener('error', handleError, { once: true });

        // 设置超时回退
        setTimeout(() => {
            if (audio.readyState < 2) {
                console.warn(`音频文件加载超时 (${audioFile})，尝试下一个`);
                this.tryPreviewAudioFiles(audioFiles, soundType, index + 1);
            }
        }, 1000);

        audio.load();
    }
    
    /**
     * 启用/禁用音频
     * @param {boolean} enabled - 是否启用
     */
    setEnabled(enabled) {
        this.isEnabled = enabled;
        this.saveSettings();
        console.log(`Audio notifications ${enabled ? 'enabled' : 'disabled'}`);
    }
    
    /**
     * 设置音量
     * @param {number} volume - 音量 (0-1)
     */
    setVolume(volume) {
        this.volume = Math.max(0, Math.min(1, volume));
        this.saveSettings();
        console.log(`Audio volume set to ${this.volume}`);
    }
    
    /**
     * 获取当前设置
     */
    getSettings() {
        return {
            isEnabled: this.isEnabled,
            volume: this.volume,
            soundType: this.currentSoundType
        };
    }
    
    /**
     * 保存设置到本地存储
     */
    saveSettings() {
        try {
            const settings = {
                isEnabled: this.isEnabled,
                volume: this.volume,
                soundType: this.currentSoundType
            };
            localStorage.setItem('pomodoro_audio_settings', JSON.stringify(settings));
        } catch (error) {
            console.error('Error saving audio settings:', error);
        }
    }
    
    /**
     * 从本地存储加载设置
     */
    loadSettings() {
        try {
            const stored = localStorage.getItem('pomodoro_audio_settings');
            if (stored) {
                const settings = JSON.parse(stored);
                this.isEnabled = settings.isEnabled !== undefined ? settings.isEnabled : true;
                this.volume = settings.volume !== undefined ? settings.volume : 0.7;
                this.currentSoundType = settings.soundType !== undefined ? settings.soundType : 'bell';
            }
        } catch (error) {
            console.error('Error loading audio settings:', error);
        }
    }
    
    /**
     * 请求音频权限（用于自动播放）
     */
    async requestPermission() {
        if (this.audioContext && this.audioContext.state === 'suspended') {
            try {
                await this.audioContext.resume();
                console.log('AudioContext resumed');
            } catch (error) {
                console.error('Failed to resume AudioContext:', error);
            }
        }
    }
    
    /**
     * 销毁音频管理器
     */
    destroy() {
        if (this.audioContext) {
            this.audioContext.close();
        }
        this.audioElement = null;
        console.log('AudioManager destroyed');
    }
}